import { ITodoData } from './typings.ts';
import TodoEvent from './js/TodoEvent';

((doc) => {
  //获取节点
  const oInput: HTMLInputElement = doc.querySelector('input');
  const oAddBtn: HTMLButtonElement = doc.querySelector('button');
  const oTodoList: HTMLElement = doc.querySelector('.todo-list');

  //初始化静态数据
  const todoData: ITodoData[] = [
    //注释静态数据改为后端请求
    // {
    //   id: 1,
    //   content: '123',
    //   completed: true
    // },
    // {
    //   id: 2,
    //   content: '345',
    //   completed: false
    // },
    // {
    //   id: 3,
    //   content: '456',
    //   completed: true
    // }
  ];

  //实例化操作数据的类
  const todoEvent: TodoEvent = new TodoEvent(todoData, oTodoList);

  //外层：浏览器的事件去调用方法，事件处理函数的绑定
  //初始化模块
  const init = (): void => {
    bindEvent();
  };

  const bindEvent = (): void => {
    oAddBtn.addEventListener('click', handleAddBtnClick, false);
    oTodoList.addEventListener('click', handleListClick, false);
  };

  //点击增加按钮时
  const handleAddBtnClick = (): void => {
    //获取输入框内容
    const val: string = oInput.value.trim();

    //有值时
    if (val.length) {
      //给todoList数组新增 一项组装后的对象
      const ret = todoEvent.addTodo(<ITodoData>{
        id: new Date().getTime(),
        content: val,
        completed: false
      });

      if (ret && ret === 1001) {
        alert('列表项已经存在');
        return;
      }

      //清空输入框内容
      oInput.value = '';
    }
  };

  //点击列表里的内容时
  const handleListClick = (e: MouseEvent): void => {
    const tar = e.target as HTMLElement;
    const tagName = tar.tagName.toLowerCase();

    if (tagName === 'input' || tagName === 'button') {
      //获取<input type="checkbox" data-id="1649171716832">里的data-id
      const id = parseInt(tar.dataset.id);

      switch (tagName) {
        //调用todoEvent实例的方法
        case 'input':
          todoEvent.toggleComplete(tar, id);
          break;
        case 'button':
          todoEvent.removeTodo(tar, id);
          break;
        default:
          break;
      }
    }
  };

  init();
})(document);
